"""
评价服务
处理评价的创建、查询、统计等业务逻辑
"""

from typing import List, Tuple, Optional, Dict, Any
from core.models.review import Review
from core.models.order import OrderStatus
from core.services.data_manager import DataManager
from core.utils.logger import debug, info, warning, error


class ReviewService:
    """评价服务类"""
    
    def __init__(self):
        self.data_manager = DataManager()
    
    def can_user_review(self, user_id: str, product_id: str) -> Tuple[bool, str]:
        """
        检查用户是否有权限评价该商品
        允许多次评价（新增不覆盖）
        
        Args:
            user_id: 用户ID
            product_id: 商品ID
            
        Returns:
            Tuple[bool, str]: (是否可以评价, 原因/订单ID)
        """
        try:
            # 检查是否购买过该商品（通过订单服务）
            from core.services.order_service import OrderService
            order_service = OrderService()
            
            # 获取用户所有订单
            all_orders = order_service.get_user_orders(user_id)
            
            # 检查是否购买过该商品（放宽检查条件，包括所有非取消状态的订单）
            for order in all_orders:
                # 允许评价未取消的订单（包括 PENDING、PAID、SHIPPED、COMPLETED）
                if order.status != OrderStatus.CANCELLED:
                    for item in order.items:
                        if item.product_id == product_id:
                            return True, order.order_id
            
            return False, "You have not purchased this product yet"
            
        except Exception as e:
            error(f"Failed to check review permission: {e}")
            return False, "Permission check failed"
    
    def add_review(self, user_id: str, product_id: str, order_id: str, 
                   rating: int, comment: str, user_name: str = "", 
                   images: List[str] = None) -> Optional[Review]:
        """
        添加评价
        
        Args:
            user_id: 用户ID
            product_id: 商品ID
            order_id: 订单ID
            rating: 评分（1-5）
            comment: 评论内容
            user_name: 用户名
            images: 图片路径列表
            
        Returns:
            Review: 创建的评价对象，失败返回None
        """
        try:
            info(f"📝 Starting to create review: user={user_id}, product={product_id}, order={order_id}, rating={rating} stars")
            
            # 验证评分
            if not isinstance(rating, int) or rating < 1 or rating > 5:
                error(f"❌ Invalid rating: {rating}")
                return None
            
            # 1. 权限验证（放宽检查，允许多次评价）
            # 不阻止评价创建，因为现在允许多次评价
            can_review, reason = self.can_user_review(user_id, product_id)
            if can_review:
                info(f"✅ Permission verification passed: user {user_id} can review product {product_id}")
            else:
                # 从订单直接创建时，即使权限检查失败也允许创建评价
                info(f"ℹ️ Permission check note: {reason}, but allowing review creation from order {order_id}")
            
            # 2. 创建评价对象
            try:
                review = Review.create_new(
                    product_id=product_id,
                    user_id=user_id,
                    order_id=order_id,
                    rating=rating,
                    comment=comment,
                    user_name=user_name,
                    images=images or []
                )
                info(f"✅ Review object created successfully: {review.review_id}")
            except Exception as e:
                error(f"❌ Failed to create review object: {e}")
                import traceback
                error(f"Exception stack: {traceback.format_exc()}")
                return None
            
            # 3. 保存到数据文件
            try:
                self._save_review(review)
                info(f"✅ Review saved successfully: {review.review_id}, product: {product_id}, rating: {rating} stars, user: {user_name}")
            except Exception as e:
                error(f"❌ Failed to save review to file: {e}")
                import traceback
                error(f"Exception stack: {traceback.format_exc()}")
                return None
            
            return review
            
        except Exception as e:
            error(f"❌ Unexpected error occurred while adding review: {e}")
            import traceback
            error(f"Exception stack: {traceback.format_exc()}")
            return None
    
    def _save_review(self, review: Review):
        """保存评价到数据文件"""
        try:
            # 加载现有评价数据
            reviews_data = self.data_manager.load_data('reviews.json') or []
            original_count = len(reviews_data)
            
            # 添加新评价
            review_dict = review.to_dict()
            reviews_data.append(review_dict)
            
            # 保存到文件
            self.data_manager.save_data('reviews.json', reviews_data)
            
            # 验证保存是否成功
            saved_data = self.data_manager.load_data('reviews.json') or []
            if len(saved_data) > original_count:
                # 查找刚保存的评价
                saved_review = None
                for r in saved_data:
                    if r.get('review_id') == review.review_id:
                        saved_review = r
                        break
                
                if saved_review:
                    info(f"✅ Review data validation successful: {review.review_id} saved to file")
                    debug(f"Saved review data: {saved_review}")
                else:
                    error(f"❌ Review data validation failed: could not find saved review {review.review_id}")
            else:
                error(f"❌ Failed to save review data: number of reviews in file did not increase")
                
        except Exception as e:
            error(f"❌ Error occurred while saving review data: {e}")
            raise
    
    def get_all_reviews(self) -> List[Review]:
        """获取所有评价"""
        reviews_data = self.data_manager.load_data('reviews.json') or []
        reviews = []
        
        for data in reviews_data:
            try:
                review = Review.from_dict(data)
                reviews.append(review)
            except Exception as e:
                error(f"Failed to parse review data: {e}")
                continue
        
        debug(f"📝 加载了 {len(reviews)} 条评价")
        return reviews
    
    def get_product_reviews(self, product_id: str, sort_by: str = 'newest') -> List[Review]:
        """
        获取指定商品的所有评价
        
        Args:
            product_id: 商品ID
            sort_by: 排序方式 ('newest', 'oldest', 'highest', 'lowest', 'helpful')
            
        Returns:
            List[Review]: 评价列表
        """
        all_reviews = self.get_all_reviews()
        product_reviews = [r for r in all_reviews if r.product_id == product_id]
        
        # 排序
        if sort_by == 'newest':
            product_reviews.sort(key=lambda x: x.created_at, reverse=True)
        elif sort_by == 'oldest':
            product_reviews.sort(key=lambda x: x.created_at)
        elif sort_by == 'highest':
            product_reviews.sort(key=lambda x: x.rating, reverse=True)
        elif sort_by == 'lowest':
            product_reviews.sort(key=lambda x: x.rating)
        elif sort_by == 'helpful':
            product_reviews.sort(key=lambda x: x.helpful_count, reverse=True)
        
        debug(f"📝 商品 {product_id} 有 {len(product_reviews)} 条评价")
        return product_reviews
    
    def get_user_reviews(self, user_id: str) -> List[Review]:
        """获取用户的所有评价"""
        all_reviews = self.get_all_reviews()
        user_reviews = [r for r in all_reviews if r.user_id == user_id]
        
        # 按创建时间倒序排列
        user_reviews.sort(key=lambda x: x.created_at, reverse=True)
        
        debug(f"👤 用户 {user_id} 有 {len(user_reviews)} 条评价")
        return user_reviews
    
    def get_user_product_review(self, user_id: str, product_id: str) -> Optional[Review]:
        """获取用户对特定商品的评价"""
        all_reviews = self.get_all_reviews()
        for review in all_reviews:
            if review.user_id == user_id and review.product_id == product_id:
                return review
        return None
    
    def get_average_rating(self, product_id: str) -> Tuple[float, int, Dict[int, int]]:
        """
        计算商品的平均评分
        
        Args:
            product_id: 商品ID
            
        Returns:
            Tuple[float, int, Dict[int, int]]: (平均分, 总评价数, 星级分布)
        """
        reviews = self.get_product_reviews(product_id)
        
        if not reviews:
            return 0.0, 0, {5: 0, 4: 0, 3: 0, 2: 0, 1: 0}
        
        # 计算平均分
        total_rating = sum(r.rating for r in reviews)
        average = total_rating / len(reviews)
        
        # 计算星级分布
        distribution = {5: 0, 4: 0, 3: 0, 2: 0, 1: 0}
        for review in reviews:
            distribution[review.rating] += 1
        
        return round(average, 1), len(reviews), distribution
    
    def get_review_statistics(self, product_id: str) -> Dict[str, Any]:
        """
        获取评价统计信息
        
        Args:
            product_id: 商品ID
            
        Returns:
            Dict: 统计信息
        """
        average, total, distribution = self.get_average_rating(product_id)
        
        return {
            'average': average,
            'total': total,
            'distribution': distribution,
            'has_reviews': total > 0
        }
    
    
    def delete_review(self, review_id: str) -> bool:
        """
        删除评价
        
        Args:
            review_id: 评价ID
            
        Returns:
            bool: 是否删除成功
        """
        try:
            reviews_data = self.data_manager.load_data('reviews.json') or []
            
            # 查找并删除评价
            original_count = len(reviews_data)
            reviews_data = [r for r in reviews_data if r.get('review_id') != review_id]
            
            if len(reviews_data) < original_count:
                self.data_manager.save_data('reviews.json', reviews_data)
                info(f"✅ Review {review_id} deleted successfully")
                return True
            else:
                warning(f"❌ Review {review_id} does not exist")
                return False
                
        except Exception as e:
            error(f"Failed to delete review: {e}")
            return False
    
    def mark_helpful(self, review_id: str) -> bool:
        """
        标记评价为有用
        
        Args:
            review_id: 评价ID
            
        Returns:
            bool: 是否标记成功
        """
        try:
            reviews_data = self.data_manager.load_data('reviews.json') or []
            
            for review_data in reviews_data:
                if review_data.get('review_id') == review_id:
                    review_data['helpful_count'] = review_data.get('helpful_count', 0) + 1
                    self.data_manager.save_data('reviews.json', reviews_data)
                    info(f"✅ Review {review_id} marked as helpful")
                    return True
            
            warning(f"❌ Review {review_id} does not exist")
            return False
            
        except Exception as e:
            error(f"Failed to mark review as helpful: {e}")
            return False
